package com.fiidee.blog.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Html的工具类
 * Created by 瑱彬 on 2015/5/27.
 */
public class HtmlUtil {
    /**
     * 在Html中找到所有img标签
     */
    public static List<String> findImgListInHtml(String html) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<String>();

        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址

        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(html);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            // Matcher m  = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src

            Matcher m = Pattern.compile("[^_]src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);

            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }

    public static String findImgsInHtml(String html) {
        List<String> picList = findImgListInHtml(html);
        StringBuffer picsBf = new StringBuffer("");
        for (String pic : picList) {
            picsBf.append(pic + ",");
        }
        if(picsBf.length() > 0){
            picsBf.deleteCharAt(picsBf.length() - 1);
        }
        return picsBf.toString();
    }

    public static String findSingleImgsInHtml(String html){
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String pic;

        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址

        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(html);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            // Matcher m  = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src

            Matcher m = Pattern.compile("[^_]src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);

            while (m.find()) {
                pic = m.group(1);
                return pic;
            }
        }
        return null;
    }

    public static String getPageHtml(int currentPage, int totalCount, int pageSize, String url,String pageParamName) {
        // 最终返回的分页导航条
        String pageNavigation = "共有" + totalCount + "条数据&nbsp;&nbsp;";
        // 记录数超过一页,需要分页
        if (totalCount > pageSize) {

            //将原先url中的分页删掉！
            StringBuffer queryStringbf = new StringBuffer(url);
            int index = queryStringbf.indexOf(pageParamName+"=");
            if (index != -1) {
                index--;
                int i = index;
                if (queryStringbf.charAt(index) == '&') {
                    queryStringbf.deleteCharAt(i);
                } else {
                    i++;
                }
                while (i < queryStringbf.length() && queryStringbf.charAt(i) != '&') {
                    queryStringbf.deleteCharAt(i);
                }

            }
            if (queryStringbf.length() - 1 == url.indexOf("?")) {
                queryStringbf.deleteCharAt(url.indexOf("?"));
            }

            url = queryStringbf.toString();


            if (url.indexOf("?") > -1) {
                // 如果url中已经包含了其他的参数,就把curPageNo参数接在后面
                url += "&";
            } else {
                // 如果url中没有别的参数
                url += "?";
            }
            // 生成一个提交页面的函数
            pageNavigation += "<script>";
            pageNavigation += "function gotoPage(page_num){";
            pageNavigation += "location.href='" + url
                    + pageParamName +"='+page_num;";
            pageNavigation += "}</script>";
        }
        pageNavigation += "每页"
                + pageSize
                + "条&nbsp;&nbsp;"
                + "当前第<select name='"+pageParamName+"' id='"+pageParamName+"' onchange='javascript:gotoPage(this.value)'>";
        int curPageNos = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount
                / pageSize + 1;
        for (int i = 1; i <= curPageNos; i++) {
            if (i == currentPage) {
                pageNavigation += "<option value='" + i + "' selected>"
                        + i + "</option>";
            } else {
                pageNavigation += "<option value='" + i + "'>" + i
                        + "</option>";
            }
        }
        pageNavigation += "</select>页&nbsp;&nbsp;共" + curPageNos
                + "页&nbsp;&nbsp;";
        // 如果不是第一页,导航条将包含"首页"和"上一页"的连接
        if (currentPage > 1) {
            pageNavigation += "[<a href=\"javascript:void(0);\" onclick=\"gotoPage(1);return false;\">首页</a>]&nbsp;"
                    + "[<a href=\"javascript:void(0);\" onclick=\"gotoPage("
                    + (currentPage - 1)
                    + ");return false;\">上一页</a>]&nbsp;&nbsp;";
        } else {
            pageNavigation += "[首页]&nbsp;[上一页]&nbsp;&nbsp;";
        }
        // 如果不是最后一页,导航条将包含"末页"和"下一页"
        if (currentPage < curPageNos) {
            pageNavigation += "[<a href=\"javascript:void(0);\" onclick=\"gotoPage("
                    + (currentPage + 1)
                    + ");return false;\">下一页</a>]&nbsp;"
                    + "[<a href=\"javascript:void(0);\" onclick=\"gotoPage("
                    + (curPageNos) + ");return false;\">末页</a>]";
        } else {
            pageNavigation += "[下一页]&nbsp;[末页]";
        }

        return pageNavigation;

    }

    public static String getSummary(String html,int limit){
        String htmlStr = html; //含html标签的字符串
        String textStr ="";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;

        try{
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
            String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

            p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); //过滤script标签

            p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); //过滤style标签

            p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); //过滤html标签

            textStr = htmlStr;
        }catch(Exception e){
            e.printStackTrace();
        }

        if(textStr.length() > (limit-2)){
            textStr = textStr.substring(0 , limit -2 )+ "..";
        }
        return textStr;//返回文本字符串

    }

    public static void main(String[] args) {
        String imgs = findImgsInHtml("打赏了1个赞<img src=\"http://static.tianyaui.com/global/dashang/images/propIcon/s/001.png\" _src=\"http://static.tianyaui.com/global/dashang/images/propIcon/s/001.png\" />留言：<span>对您的敬仰如滔滔江水连绵不绝。</span></p><p class=\"msg\"><a href=\"http://www.tianya.cn/19322090\">古钟生</a>对<a href=\"http://www.tianya.cn/19322090\">古钟生</a>的帖子<a href=\"http://bbs.tianya.cn/post-1018-1225-1.shtml\">《天涯论坛》</a>打赏了100个赏金<img src=\"http://static.tianyaui.com/global/dashang/images/propIcon/s/000.png\" />。</p> \n");
        System.out.println(imgs);
    }
}
